package 牛客_面试必刷.Month07.day08;

public class 删除链表中倒数第K个节点 {
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        ListNode node = new ListNode(0);
        node.next = head;
        ListNode fast = find(head,n);
        ListNode slow = node;
        while(slow.next != fast){
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return node.next;
    }

    public ListNode find(ListNode head,int k){
        ListNode fast = head;
        ListNode slow = head;
        while(k-- > 0){
            if(fast == null) return null;
            fast = fast.next;
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
